﻿using UnityEngine;
using UnityEditor;

namespace GameToolkit.Editor
{
    [CustomPropertyDrawer(typeof(NavAreaTypeAttribute))]
    public class NavAreaTypeDrawer : PropertyDrawer
    {
        //StringBuilder builder = new StringBuilder();
        string[] areaNames;
        int[] areaIds;
        int areaIndex;
        
        void GetAreaNames(int area)
        {
            areaNames = GameObjectUtility.GetNavMeshAreaNames();
            if(areaIds == null || areaIds.Length != areaNames.Length)
                areaIds = new int[areaNames.Length];
            areaIndex = -1;
            for (var i = 0; i < areaNames.Length; i++)
            {
                areaIds[i] = GameObjectUtility.GetNavMeshAreaFromName(areaNames[i]);
                if (area == areaIds[i])
                    areaIndex = i;
            }
        }

        //int IndexOfId(int id)
        //{
        //    for (int i = 0; i < areaIds.Length; i++)
        //    {
        //        if (areaIds[i] == id)
        //            return i;
        //    }
        //    return -1;
        //}

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);

            int lv = EditorGUI.indentLevel;
            //builder.Remove(0, builder.Length);
            //for (int i = 0; i < lv; i++)
            //{
            //    builder.Append("    ");
            //}
            //EditorGUI.indentLevel = 0;
            //builder.Append(label.text);
            //label.text = builder.ToString();
            position = EditorGUI.PrefixLabel(position, label);
            if (property.propertyType == SerializedPropertyType.Integer)
            {
                GetAreaNames(property.intValue);
                position.width -= 80;
                int index = EditorGUI.Popup(position, areaIndex, areaNames);
                if (index != areaIndex && index >= 0)
                    property.intValue = areaIds[index];
                position.x += position.width;
                position.width = 80;
                EditorGUI.LabelField(position, areaIds[index].ToString(), DevilEditorUtility.HintStyle("label"));
            }
            else
            {
                EditorGUI.LabelField(position, "Use Integer Instead of " + property.propertyType);
            }
            EditorGUI.indentLevel = lv;

            EditorGUI.EndProperty();
        }
    }
}